from datetime import datetime
from typing import Optional

from fastapi import Query
from fastapi_utils.api_model import APIModel
from pydantic import BaseModel, ConfigDict, Field, field_validator


class RoleQueryParams:
    def __init__(
        self,
        role_name: Optional[str] = Query(None, alias="roleName"),
        role_code: Optional[str] = Query(None, alias="roleCode"),
        page: int = Query(1),
        limit: int = Query(10),
    ):
        self.role_name = role_name
        self.role_code = role_code
        self.page = page
        self.limit = limit


class RoleOutSchema(APIModel):
    model_config = ConfigDict(from_attributes=True)

    id: int = Field(description="角色ID")
    name: str = Field(description="角色名称")
    code: str = Field(description="角色编码")
    enable: int = Field(description="是否启用")
    remark: Optional[str] = Field(default=None, description="备注")
    details: Optional[str] = Field(default=None, description="详情")
    sort: int = Field(description="排序")
    create_time: datetime = Field(description="创建时间")
    update_time: datetime = Field(description="更新时间")


class RoleSaveSchema(BaseModel):
    details: Optional[str] = Field(None, description="详情")
    enable: int = Field(1, description="是否启用")
    role_code: str = Field(..., description="角色编码")
    role_name: str = Field(..., description="角色名称")
    sort: int = Field(0, description="排序")

    @field_validator("role_code")
    def validate_role_code(cls, v):
        if not v:
            raise ValueError("角色编码不能为空")
        return v

    @field_validator("role_name")
    def validate_role_name(cls, v):
        if not v:
            raise ValueError("角色名称不能为空")
        return v


class RoleUpdateSchema(BaseModel):
    roleId: int = Field(..., description="角色ID")
    details: Optional[str] = Field(None, description="详情")
    enable: int = Field(1, description="是否启用")
    roleCode: str = Field(..., description="角色编码")
    roleName: str = Field(..., description="角色名称")
    sort: int = Field(0, description="排序")

    @field_validator("roleId")
    def validate_role_id(cls, v):
        if v <= 0:
            raise ValueError("角色ID必须大于0")
        return v


class RolePowerSaveSchema(BaseModel):
    powerIds: str = Field(..., description="权限ID列表，用逗号分隔")
    roleId: int = Field(..., description="角色ID")

    @field_validator("roleId")
    def validate_role_id(cls, v):
        if v <= 0:
            raise ValueError("角色ID必须大于0")
        return v


class RoleEnableDisableSchema(BaseModel):
    roleId: int = Field(..., description="角色ID")
